package server.thread;

import server.Request;
import server.Response;
import server.container.Mapper;
import server.servlet.HttpServlet;
import server.servlet.Servlet;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @description:
 * @author: Archie Wan
 * @time: 2020/12/27 15:27
 */
public class RequestProcessor extends Thread {
    
    private Socket socket;
    private Map<String, HttpServlet> servletMap;
    private Mapper mapper;
    
    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap, Mapper mapper) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.mapper = mapper;
    }
    
    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();
        
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
    
            Servlet servlet = mapper.getServlet(request);
            // 静态资源处理
            if(servlet == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                servlet.service(request, response);
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
